<template>
  <div class="main-wrapper">
    <div class="report-header">
        <p class="title">作业名称： 
          <span style="font-weight:bold"> {{ overview.session_name }} </span>  &nbsp;
          <el-tooltip v-if="this.loginRole === 'admin'" class="item" effect="dark" content="发送评测报告" placement="top-start">
            <i  @click="informMetricReport" class="iconfont icon-infofill" style="cursor:pointer"></i>
           </el-tooltip>
        </p>
    </div>
    <div class="report-content">
      <!-- 运行总览 和 指标统计 -->
      <div class="report-content-overview">
        <div class="overview-left">
          <p class="overview-title">评测总览</p>
          <div class="overview-chart-box">
            <div class="overview-chart">
              <p class="chart-title">运行状态</p>
              <pie-chart class="chart" v-if="runPieData.length>0" :transferPieData="runPieData" :setting="runPieSet" />
              <div v-else class="empty-data" >
                <img src="@/assets/img/empty-status.svg" alt="">
              </div>
          </div>
          </div>
        </div>
        <div class="overview-right">
          <p class="overview-title">指标统计</p>
          <ul class="overview-statistic">
            <li class="overview-statistic-li" v-for="(item, index) in statistics" :key="index">
              <p class="statistic-name">
                <img :src="item.icon" alt="">
                {{ item.name }}
              </p>
              <p class="statistic-value">
                <span>{{ item.value }}</span>{{ item.unit }}
              </p>
            </li>
          </ul>
        </div>
      </div>
      <!-- 详情 -->
      <div class="report-content-detail">
        <p class="overview-title">评测详情</p>
        <el-tabs type="card" @tab-click="handleChangeTabs" v-model="activeTab">
          <!-- 通过型 结果 -->
          <el-tab-pane label="通过型" name="passMetric">
            <p class="overview-title run-result-title" style="display:inline-block">总览</p>
            <el-button class="detail-btn" style="float:right" size="small" @click="openAllResult"> 指标通过结果</el-button> 
            <columnChart class="metric-column" v-if="columnPieData.length>0" :transferData="columnPieData" />
            <div v-else style="text-align:center;margin-top: 30px;">
              <img src="@/assets/img/empty-status.svg" alt="">
            </div>
            <p class="overview-title run-result-title">失败结果</p>
            <div class="fail-result-box">
              <ul class="fail-metric-left">
                <li class="metric-title-li">指标类型</li>
                <li :class="[{ 'active': activePassMetricCategory === item.cnName }, 'metric-category-li']"
                  v-for="(item, index) in metricFailedResult" :key="index" @click="changeMetricCategory(item)">
                  {{ item.cnName }}
                </li>
              </ul>
              <div class="fail-metric-right">
                <el-table :data="passfailMetricTable" tooltip-effect="dark" style="width: 100%" :border="true"
                  :header-cell-class-name="headerCellClassName" :cell-class-name="cellClassName">
                  <el-table-column label="度量指标名称" prop="metricDisplayName" width="300px">
                  </el-table-column>
                  <el-table-column label="通过率" width="300px">
                    <template slot-scope="scope">
                      {{ (scope.row.passRate*100).toFixed(2) }}% ({{ scope.row.totalCount - scope.row.failCount }} / {{ scope.row.totalCount}} )
                    </template>
                  </el-table-column>
                  <el-table-column label="失败总数" prop="failCount" width="200px">
                  </el-table-column>

                  <el-table-column label="失败详情">
                    <template slot-scope="scope">
                      <span class="operation-link" @click="openFailDetail(scope.row.metricName, scope.row.metricDisplayName)">查看</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
          <!-- 数值型 结果 -->
          <el-tab-pane label="数值型" name="numerical">
            <p class="overview-title run-result-title">运行结果</p>
            <div class="fail-result-box numerical-result-box">
              <div class="numerical-metric-left fail-metric-left">
                <ul class="numerical-ul-first">
                  <li class="metric-title-li">指标类型</li>
                  <li :class="[{'active': activeFirstNumericalName === item.metricTypeCnName},'metric-category-li']" v-for="(item, index) in firstNumericalData.items" :key="index"
                    @click="firstNumericalCategory(item)">
                    {{ item.metricTypeCnName }}
                    <span class="icon-right"> > </span>
                  </li>
                </ul>
                <ul class="numerical-ul-second">
                  <li class="metric-title-li">指标名称</li>
                  <li :class="[{'active': activeSecondNumericalName === ele.metricCnName},'metric-category-li']" v-for="(ele, index) in secondNumericalData" :key="index"
                    @click="secondNumericalCategory(ele)">
                    {{ ele.metricCnName }}
                    
                  </li>
                </ul>
              </div>
              <div class="numerical-metric-right">
                <el-table :data="numericalMetricTable" tooltip-effect="dark" style="width: 100%" :border="true"
                  :header-cell-class-name="headerCellClassName" :cell-class-name="cellClassName">
                  <el-table-column v-for="(value, index) in numericalMetricColumns" :label="value.name" :prop="value.prop"
                    :key="index" :width="value.width">
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 通过型 的失败详情 弹窗 -->
    <FailDetailDialog :dialogVisible="failDetailVisible" :currentFailMetricName="currentFailMetricName" :currentFailMetricDisplayName="currentFailMetricDisplayName" :sessionId="session_id" @closeDialog="closeFailDetailDialog" />
    <!-- 所有指标的详情 弹窗 -->
    <allResultDialog :dialogVisible="allResultVisible" :sessionId="session_id" @closeDialog="closeAllResultDialog" />

  </div>
</template>
<script>
import metricIcon1 from '@/assets/img/metric-icon1.svg';
import metricIcon2 from '@/assets/img/metric-icon2.svg';
import metricIcon3 from '@/assets/img/metric-icon3.svg';
import metricIcon4 from '@/assets/img/metric-icon4.svg';
import { failCause } from '@/business/failCause'             // 失败原因 的 假数据
import pieChart from '@/widgets/pie-chart.vue'
import columnChart from '@/widgets/column-chart.vue'
import FailDetailDialog from './components/failDetailDialog.vue';
import allResultDialog from './components/allResultDialog.vue';
import { getReport, informMetricReport ,getNumerical} from '@/api/report';

import { Message } from 'element-ui'
export default {
  name: 'TaskReport',
  components: { pieChart, columnChart, FailDetailDialog, allResultDialog },
  data() {
    return {
      session_id: '',
      failDetailVisible: false,
      allResultVisible: false,
      runPieData: [], // 总运行pie展示数据
      failPieData: [],  // 失败运行pie展示数据
      runPieSet: {
        color: ['#5364B0', '#da4040', '#5B8FF9'],
        text: '运行Task总数'
      },
      failPieSet: {
        color: ['#da4040', '#ee6767', '#ec9696', '#da1313'],
        text: '失败总数'
      },
      statistics: [
        {
          name: '通过型指标',
          value: 0,
          unit: '个',
          icon: metricIcon1
        },
        {
          name: '场景通过率',
          value: 0,
          unit: '%',
          icon: metricIcon2
        },
        {
          name: '数值型指标',
          value: 0,
          unit: '个',
          icon: metricIcon3
        },
        {
          name: '运行里程',
          value: 0,
          unit: 'KM',
          icon: metricIcon4
        },
      ],
      activeTab: 'passMetric',
      metricFailedResult: [], // 通过型的fail 指标数据
      activePassMetricCategory: '', // 选中的 通过型 fail的类型
      passfailMetricTable: [],  // 右下角 通过型 fail 列表
      firstNumericalData: [],         // 数值型的 左侧的 指标类型(1级)
      activeFirstNumericalName: '', // 数值型的 左侧的 指标类型（点击选中）
      activeSecondNumericalName: '', // 数值型的 左侧的 指标名称（点击选中）
      secondNumericalData: [], // 数值型的 左侧的 指标名称（2级）
      numericalMetricTable: [],      // 数值型的 表格数据
      numericalMetricColumns: [
      {
          name: '评价结果',
          prop: 'idCnName',
          width: '500px'
        },
        {
          name: '有效计数',
          prop: 'validCount',
          width: '200px'
        },
        {
          name: '计算结果',
          prop: 'value',
        }
      ],
      passFailMetric: [],
      overview: {},
      columnPieData: [],
      currentFailMetricName: '',
      currentFailMetricDisplayName: '',
      loginRole: '',
    }
  },
  watch: {
    '$route.params.sessionId':function(newVal){
      if(newVal){
        // 数据回到初始状态
        this.overview = {}
        this.session_id = newVal
        this.passfailMetricTable = []
        this.activeFirstNumericalName = ''
        this.activeSecondNumericalName = ''
        this.numericalMetricTable = []
        this.secondNumericalData = []
        this.activeTab= 'passMetric'
        this.getReport()
        this.getNumerical()
      }
    }
  },
  created() {
    this.session_id = this.$route.params.sessionId
    this.getReport()
    this.formateFailCause()
    
    // 处理数值型 结果的数据 
    this.getNumerical()
  },
  methods: {
    cellClassName() {
      return 'body-cell-custom'
    },
    headerCellClassName() {
      return 'header-cell-custom'
    },
    getReport() {
      getReport({ session_id: this.session_id }).then(res => {
        this.loginRole = res.role
        this.passFailMetric = res.result.successMetric
        this.overview = res.result.reportOverview.all
        // 处理fail 指标数据
        this.metricFailedResult = res.result.metricFailedResult.core.items
        // 增加 默认第一条数据
        if(this.metricFailedResult && this.metricFailedResult.length>0){
          this.activePassMetricCategory = this.metricFailedResult[0].cnName
          this.passfailMetricTable = this.metricFailedResult[0].normal
        }
        // 处理饼图数据
        if(this.overview.taskCount !== 0){
          this.runPieData = [
            { type: '运行成功', value: this.overview.successTaskCount },
            { type: '运行失败', value: this.overview.failTaskCount }
          ]
        }else {
          this.runPieData = []
        }
        // 处理柱状图数据
        this.columnPieData = this.formatColumnData(this.passFailMetric)
        // 处理指标统计
        this.statistics[0].value = this.overview.passFailCount
        this.statistics[1].value = Math.round(this.overview.successTaskCount / this.overview.taskCount * 100) || 0
        this.statistics[2].value = this.overview.numericCount
        this.statistics[3].value = this.overview.odometers.toFixed(2)
      })
    },
    // 处理 失败原因的pie data
    formateFailCause(){
      const failTaskData = failCause.failTaskRatioList
      this.failPieData = failTaskData.map((item) => {
        return {
          type: item.failName,
          value: item.failCount
        }
      })
    },
    // 打开失败详情弹窗
    openFailDetail(value1,value2) {
      this.failDetailVisible = true
      this.currentFailMetricName = value1
      this.currentFailMetricDisplayName = value2
    },
    // 关闭失败详情弹窗
    closeFailDetailDialog() {
      this.failDetailVisible = false
      this.currentFailMetricName = ''
      this.currentFailMetricDisplayName = ''
    },
    // 打开 全部详情弹窗
    openAllResult(){
      this.allResultVisible = true
    },
    // 关闭 全部详情弹窗
    closeAllResultDialog() {
      this.allResultVisible = false
    },
    informMetricReport() {
      informMetricReport({ session_id: this.session_id }).then(res => {
        Message({
        message: '评测报告发送成功',
        type: 'success',
        center: true
      })
      });
    },
    // 处理 柱状图所需数据
    formatColumnData(data) {
      if(data && data.length>0){
        let res = data.map((item) => {
          return [
            {
              text: item.metricName,
              value: item.passNum,
              type: '通过'
            },
            {
              text: item.metricName,
              value: item.notPassNum,
              type: '未通过'
            }
          ]
        }).flat()
        return res
      }else {
        return []
      }
    },
    // 通过型 fail左侧列 点击
    changeMetricCategory(data) {
      this.activePassMetricCategory = data.cnName
      this.passfailMetricTable = data.normal
    },
    // 数值型 第一级 点击
    firstNumericalCategory(data) {
      this.activeFirstNumericalName = data.metricTypeCnName
      this.secondNumericalData = data.metricDetail
    },
    // 数值型 第二级 点击
    secondNumericalCategory(data){
      this.activeSecondNumericalName = data.metricCnName
      this.numericalMetricTable = data.metricIdList[0].metricThreeLevelList 
    },
    // 切换tab (通过型/数值型)
    handleChangeTabs(tab, event) {
      if(tab.name === 'passMetric'){
        // this.activeFirstNumericalName = ''
        // this.activeSecondNumericalName = ''
      }
    },
    getNumerical(){
      getNumerical({ session_id: this.session_id }).then(res => {
        this.firstNumericalData = res.data
        // 增加 默认第一条数据
        if(this.firstNumericalData.items && this.firstNumericalData.items.length >0){
          this.activeFirstNumericalName = this.firstNumericalData.items[0].metricTypeCnName
          this.secondNumericalData = this.firstNumericalData.items[0].metricDetail
          this.activeSecondNumericalName = this.firstNumericalData.items[0].metricDetail[0].metricCnName
          this.numericalMetricTable = this.firstNumericalData.items[0].metricDetail[0].metricIdList[0].metricThreeLevelList 
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/vars.scss';
.report-header{
  padding:20px;
  border-bottom: 1px solid rgb(242, 243, 248);
  font-size: 16px;
  color: #3d3d3d;
}
.report-content {
  padding: 20px;
  .empty-data{
    text-align: center;
    margin-top: 60px;
  }
  .overview-title {
    font-size: 16px;
    color: $primary-color;
    margin-bottom: 15px;
    font-weight: bold;
  }

  .report-content-overview {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .overview-left,
    .overview-right {
      width: 49%;
    }

    .overview-chart-box {
      background: rgb(242, 243, 248);
      height: 300px;
      display: flex;
      justify-content: center;
      .overview-chart{
        width: 50%;
        text-align: center;
        .chart-title{
          margin-top: 40px;
          font-weight: bold;
        }
      }
    }

    .overview-statistic {
      height: 300px;
      background: rgb(242, 243, 248);
      padding: 15px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      flex-wrap: wrap;

      .overview-statistic-li {
        border: 1px solid #ddd;
        border-radius: 4px;
        padding: 24px;
        width: 48%;
        height: 120px;

        &:nth-child(odd) {
          margin-right: 2%;
        }

        &:nth-child(-n +2) {
          margin-bottom: 15px;
        }

        >p {
          font-size: 18px;
          line-height: 1.8;

          >img {
            margin-right: 6px;
          }
        }

        .statistic-value {
          margin-left: 50px;

          >span {
            color: $primary-color;
            font-weight: bold;
            margin-right: 5px;
          }
        }
      }
    }

    .metric-column {
      width: 100%;
      height: 400px !important;
    }
  }

  .run-result-title {
    padding-left: 8px;
    border-left: 2px solid $primary-color;
    margin-top: 10px;
  }

  .fail-result-box {
    height: 310px;
    display: flex;
    justify-content: space-between;

    .fail-metric-left {
      overflow: auto;
      width: 300px;
      border: 1px solid rgb(242, 243, 248);

      .metric-category-li {
        padding: 6px 20px;
        font-size: 14px;
        line-height: 2.2;
        .icon-right{
          float:right;
        }
        &:hover {
          cursor: pointer;
        }

        &.active {
          color: $primary-color;
          font-weight: bold;
          cursor: pointer;
        }
      }

      .metric-title-li {
        padding: 6px 20px;
        font-size: 14px;
        line-height: 2.2;
        padding-top: 10px;
        border-bottom: 1px solid rgb(242, 243, 248);
      }
    }

    .fail-metric-right {
      width: calc(100% - 320px);
      overflow: auto;

      .el-table {
        height: 100% !important;
      }
    }
    .numerical-metric-left {
      width: 600px;
      display: flex;
      justify-content: flex-start;
    }
    .numerical-metric-right{
      width: calc(100% - 620px);
    }
  }
  .numerical-result-box{
    height:630px;
    .numerical-ul-first{
      width:50%;
      border-right: 1px solid rgb(242, 243, 248);
    }
    .numerical-ul-second{
      width:50%;
    }
  }

  .operation-link {
    cursor: pointer;
    color: $primary-color;
  }


}</style>